import { Injectable } from '@angular/core';
import { LeanCloudService } from 'app/utils/lean-cloud.service'
import { Observable } from 'rxjs'
import { PageService } from 'app/utils/page.service'

@Injectable()
export class ReportManageService {

  constructor(
    private leanCloudService: LeanCloudService
  ) { }

  /**
   * 获取周报列表
   */
  getReports() {
    return this.leanCloudService.send(
      ({ leancloud }) => {
        let query = leancloud.Query('report')
        query.include('team')
        query.include('team.admin')
        return query.find()
      }
    )
  }

  /**
   * 获取周报
   * @param id
   */
  getReport(id) {
    return this.leanCloudService.send(
      ({ leancloud }) => leancloud.Query('report').get(id)
    )
  }

  /**
   * 获取用户管理团队
   */
  getUserTeams() {
    return this.leanCloudService.send(
      async ({ leancloud }) => {
        let user = leancloud.User.current()

        let userQuery = leancloud.Query('user')
        userQuery.equalTo('auth', user);

        let query = leancloud.Query('team')

        query.matchesQuery('admin', userQuery);
        let teams = await query.find()
        if (teams.length === 0) {
          return leancloud.Query('team').find()
        }
        return teams
      }
    )
  }


  /**
   * 获取该团队项目
   * @param team
   */
  getTeamProjects(team) {
    return this.leanCloudService.send(
      ({ leancloud }) => {
        let query = leancloud.Query('team_project_map')
        query.equalTo('team', team);
        query.include('project')
        return query.find().then(data => data.map(x => x.get('project')))
      }
    )
  }

  /**
   * 获取团队成员
   */
  getTeamUsers(team) {
    return this.leanCloudService.send(
      ({ leancloud }) => {
        let query = leancloud.Query('team_user_map')
        query.equalTo('team', team);
        query.include('user')
        return query.find().then(data => data.map(x => x.get('user')))
      }
    )
  }

  /**
   * 保存周报数据
   * @param param
   */
  async saveReport({ id, start, end, team }: { id?, start?, end?, team?}) {
    if (!id) {
      let query = this.leanCloudService.Query('report')
      query.equalTo('start', start)
      query.equalTo('end', end)
      query.equalTo('team', team)
      if(await query.count()){
        return Promise.reject('已存在重复周报')
      }
    }


    let report = this.leanCloudService.Object.createWithoutData('report', id)

    start && report.set('start', start)
    end && report.set('end', end)
    team && report.set('team', team)

    return report.save()
  }

  generateCompleteTasks(report) {
    return this.leanCloudService.send(
      ({ leancloud }) => {
        let time = 60 * 60 * 24 * 7 * 1000
        let start = report.get('start') - time
        let end = report.get('end') - time

        let reportQuery = leancloud.Query('report')
        reportQuery.equalTo('start', start);
        reportQuery.equalTo('end', end);

        let query = leancloud.Query('report_plan_map')
        query.matchesQuery('report', reportQuery);
        query.include('task')
        return query.find()
          .then((data: Array<any>) => data.map(x => x.get('task')))
          .then((data => data.map(task => {
            let complete = this.leanCloudService.Object.createWithoutData('report_complete_map')
            complete.set('report', report)
            complete.set('task', task)
            complete.fetchWhenSave = true
            return complete
          })))
          .then(tasks => {
            if (tasks) {
              return this.leanCloudService.Object.saveAll(tasks)
            } else {
              return []
            }
          })
      }
    )
  }

  /**
   * 获取完成任务列表
   */
  getCompleteTasks(report) {
    return this.leanCloudService.send(
      ({ leancloud }) => {
        let query = leancloud.Query('report_complete_map')
        query.equalTo('report', report)
        query.include('report')
        query.include('task')
        query.include('task.project')
        query.include('task.user')
        return query.find()
      }
    )
  }

  /**
   * 获取计划任务列表
   */
  getPlanTasks(report) {
    return this.leanCloudService.send(
      ({ leancloud }) => {
        let query = leancloud.Query('report_plan_map')
        query.equalTo('report', report)
        query.include('report')
        query.include('task')
        query.include('task.project')
        query.include('task.user')
        return query.find()
      }
    )
  }
  /**
   * 保存完成任务
   */
  saveCompleteTask({ id, report, task, complete, remark }: { id?, report, task, complete?, remark?}) {
    let object = this.leanCloudService.Object.createWithoutData('report_complete_map', id)
    !id && object.set('report', report)
    !id && object.set('task', task)
    complete !== undefined && object.set('complete', complete)
    remark !== undefined && object.set('remark', remark)

    return object.save()
  }

  /**
   * 保存计划任务
   */
  savePlanTask({ id, report, task }: { id?, report, task }) {
    let object = this.leanCloudService.Object.createWithoutData('report_plan_map', id)
    !id && object.set('report', report)
    !id && object.set('task', task)
    return object.save()
  }

  /**
   * 保存任务
   */
  saveTask({ team, project, user, date, content }: { team, project, user, date, content }) {
    let task = this.leanCloudService.Object.createWithoutData('task')
    task.set('team', team)
    task.set('project', project)
    task.set('user', user)
    task.set('date', date)
    task.set('content', content)
    return task.save()
  }
}
